<template>
  <div class="mains">
    <div class="search-box">
       <div class="start-time">
        <span class="titles">状态:</span>
        <el-select v-model="form.rState"  placeholder="请选择">
          <el-option v-for="item in option2" :key="item.id" :label="item.name" :value="item.templateId"
            :disabled="!item.userId.includes(userRole)" />
        </el-select>
       </div>
       <div class="timeType">
        <span class="titles">年度:</span>
        <el-select v-model="form.val"  placeholder="请选择">
          <el-option v-for="item in option3" :key="item" :label="item" :value="item" />
        </el-select>
       </div>
       <div class="types">
        <span class="titles">经开区名称:</span>
        <el-select v-model="form.developArea"  placeholder="请选择">
          <el-option v-for="item in option1" :key="item" :label="item" :value="item" />
        </el-select>
       </div>
       <div class="selectBox">
        <span class="titless">上报时间: </span>
        <el-date-picker style="width: 200px" v-model="value1"  type="datetimerange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="timeChoose" />
      </div>
     </div>
     <div class="button-box">
        <el-button type="info"  @click="clearAll">重置</el-button>
        <el-button type="danger" @click="searchAll">搜索</el-button>
     </div>
    <div class="tableBox">
      <el-table :data="list" style="width: 98%;margin: 10px auto"
      :header-cell-style="{
          background: '#E7F2FF',
          color: 'black',
        }"
        v-loading="loading"
         border>
        <el-table-column fixed prop="developArea" label="开发区名称" width="200" align="left" />
        <el-table-column prop="val" label="年度" width="100" align="center" />
        <el-table-column prop="name" label="报表类型" width="550" align="left" />
        <el-table-column prop="reportTime" label="上报时间" width="200" align="center" />
        <el-table-column prop="checkTime" label="审核时间" width="200" align="center" />
        <el-table-column label="状态" width="100" align="center"> 
           <template #default="scope" >
           <span v-if = "scope.row.checkInfoList&&scope.row.rState == '2' && scope.row.checkInfoList[0].shState == 2">
              已审批
          </span>
          <span v-else>
              {{ scope.row.rState == '1' ? '未上报' : scope.row.rState == '2'?'未审批':'已审批'}}
          </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="300" width="auto" align="center">
           <!-- 省级市省级 -->
           <template #default="scope" v-if="userRole!='3'">
             <el-button link type="primary" size="small" v-if="userRole!='3'||scope.row.rState != '1'" @click="toCheck(scope.row,1)">查看</el-button>
              <el-button link type="primary" size="small" @click="postPass(scope.row)"
              v-if="scope.row.rState=='2'&& scope.row.checkInfoList[0].shState != 2">通过</el-button>
              <el-button link type="primary" size="small" @click="returnBth(scope.row)" style="color: red;"
              v-if="scope.row.rState == '2' && scope.row.checkInfoList[0].shState != '2'">退回</el-button>
              <el-button link type="primary" size="small" @click="download(scope.row)">导出</el-button>
              <el-button link type="primary" size="small" @click="showDig(scope.row)">查看补录</el-button>
            </template>
            <!-- 区级 -->
            <template #default="scope" v-else>
             <el-button link type="primary" size="small" v-if="scope.row.rState != '1'" @click="toCheck(scope.row,1)">查看</el-button>
             <el-button link type="primary" size="small" @click="toCheck(scope.row,false)"
             v-if="scope.row.rState == '1'" >{{scope.row.tstate == '2'?'编辑':'填报'}}</el-button> 
             <el-button link type="primary" size="small" @click="toReport(scope.row)"   v-if="scope.row.rState == '1' && scope.row.tstate == '2'" >上报</el-button>
             <el-button link type="primary" size="small" @click="download(scope.row)">导出</el-button>
             <el-button link type="primary" size="small" @click="showDig(scope.row)">补录</el-button>
            </template>
        </el-table-column>
      </el-table>
      <div class="pagination-box">
        <el-pagination :total="totals" layout="prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" v-model:current-page="form.currentPage" v-model::page-size="form.pageNum" />
      </div>
      <el-dialog v-model="dialogVisible" title="补录" width="40%" :before-close="handleClose" style="height: auto;">
        <div class="showDig">
      <div class="uploadbox">
        
        <el-upload v-if="userRole=='3'" class="upload-demo" drag action="" :limit="maxNum" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx, .xls,.xlsx"
          multiple :on-change="changeFile" :auto-upload='false' v-model:file-list="fileList"
          :before-remove="beforeRemove">
          <img src="../../assets/container.png" />
          <div class="bthUpload">选择文件</div>
          <upload-filled />
          <div class="el-upload__text">
            点击或将文件拖拽到这里上传
          </div>
        </el-upload>  
        <div class="oldFile">
         已上传文件：<br> 
         <div style="margin: 10px 0;" v-for="(item,index) in  filesName" :key="index">
          <span style="margin-right: 10px;">{{item}}</span>
          <el-button type="danger" @click="downFile (item)" >下载</el-button>
        </div>
        </div>  
      </div>
        </div>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false" v-if="userRole=='3'">取消</el-button>
        <el-button @click="dialogVisible = false" v-else>退出</el-button>
        <el-button type="primary" @click="sureFile" v-if="userRole=='3'">
            确定补录
        </el-button>
      </span>
           </template>
      </el-dialog>
      <el-dialog v-model="dialogVisible5" title="退回" width="30%" :before-close="handleClose">
       退回理由： <el-input v-model="formReturn.reason" autocomplete="off" style="width: 300px" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible5 = false">取消</el-button>
        <el-button type="primary" @click="sureReturn">
          退回
        </el-button>
      </span>
    </template>
  </el-dialog>
  <div class="showBox" v-if="showSuccess">
      <img src="../../assets/images/Check-Circle-Fill.png" alt="">
      <span>填报成功</span>
    </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.pagination-box {
  width: 90%;
  margin: 30px auto;

  ::v-deep(.el-pagination) {
    float: right;
  }
}
.mains{
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  padding: 30px;
  .search-box{
    width: 100%;
    display: flex;
    margin-bottom: 20px;
    justify-content: space-around;
    align-items: center;
 }
 .titles{
    margin-right: 10px;
 }
 .tableBox{
  width: 100%;
 }
 .button-box{
  width: 100%;
  display: flex;
  justify-content: right;
  margin: 20px 0;
  padding-right: 2%;
 }
 .showBox {
  width: 326px;
  height: 208px;
  position: fixed;
  background-color: white;
  box-shadow: 0px 3px 29px 10px #D9D9D9;
  left: calc(50% - 163px);
  top: calc(50% - 104px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: 500;
  z-index: 9999;
  img {
    display: block;
    width: 70px;
    height: 70px;
  }
}
}
.uploadbox{
  width: 100%;
  margin: 20px;
  margin-right: 20px;
  display: flex;
  .oldFile{
    margin-left: 20px;
  }
}
.showDig{
  display: flex;
}
</style>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { sticalQ, sticalS,upAssesFile,wangeditorFile, getzheTb, statisticalexport ,statisticalsetFile,reportpublish,statisticalcheck,statisticalFindbyId,statisticalpublish} from '../../util/api'
import { ElMessage, ElMessageBox } from "element-plus"
import { useStore } from '@/store'
import { useRouter } from "vue-router";
const userRole = useStore().state.userInfo.userRole
const router = useRouter();
const loading: any = ref(false)
const value1: any = ref([])
const list: any = ref([])//评估列表
const option1: any = ref([])//开发区列表
const totals:any=ref(0)
//上传的文件列表
const fileList = ref([])
//最大上传数
const maxNum = ref(3)
//上传的文件
const uploadFile = ref([])
const option2: any = ref([
  { name: '未上报', id: '1', templateId: '1', userId: ['1','2', '3'] },
  { name: '未审批', id: '2', templateId: '2', userId: ['1', '2','3'] },
  { name: '已审批', id: '5', templateId: '5', userId: ['1', '2', '3'] },
])
//退回或者通过的参数
const formReturn:any=ref({
   id:'',
   shResult:'',
   reason:''
})
//填报弹窗
const showSuccess:any=ref(false)
const option3: any = ref([])//年度
const form: any = ref({
  currentPage:1,
  pageNum:10,
  reportTimeStart: '', // 开始时间
  reportTimeEnd: '',  // 截止时间
  developArea: '',//开发区
  rState: '',//状态
  val: ''//年度
})
//需要补录的id
const setFile: any = ref('')
const filesName:any = ref([])
//补录弹窗
const dialogVisible: any = ref(false)
//退回弹窗
const dialogVisible5: any = ref(false)
const showDigs:any=ref({})
//获取评估列表
const getAssess = async () => {
  loading.value=true
  if (userRole != 3) {
    var res: any = await sticalS(form.value)   
  } else {
    var res: any = await sticalQ(form.value)
  }
  if (res.code != '200') return false
  list.value = res.data.content
  totals.value = parseInt(res.data.totalElements);
  loading.value=false
  if (list.value) {
    list.value.forEach((item: any) => option3.value.includes(item.val) ? '' : option3.value.push(item.val))
  }
  console.log(list.value)
}
//获取开发区下拉列表数据
const getSelect = async () => {
  let res: any = await getzheTb()
  // console.log(res)
  if (res) {
    res.data.forEach((item: any) => option1.value.push(item.username))
  }
}
//分页
const handleSizeChange = (val: number) => {
  form.value.pageNum = val;
  getAssess();
};
const handleCurrentChange = (val: number) => {
  form.value.currentPage = val;
  getAssess();
};
//查询按钮
const searchAll = async () => {
  getAssess()
}
//清空所有参数
const clearAll = async () => {
  form.value = {
    reportTimeStart: '', // 开始时间
    reportTimeEnd: '',  // 截止时间
    developArea: '',//开发区
    rState: '',//状态
    val: ''//年度
  }
  value1.value = []
  getAssess()
}
// 导出 
const download = async(item: any) => {
  let res:any = await statisticalexport(item.id)
    console.log(res)
    let fileName = item.name + ".xlsx"
    if (res) {
      const a = document.createElement('a')
      a.href = URL.createObjectURL(res)
      a.setAttribute(
              'download',
              fileName
            )
            document.body.appendChild(a)
            a.click();
            document.body.removeChild(a)
    } else {
      ElMessage.error(res.errMsg)
    }
}
const toCheck = (item: any,isCheck:any) =>{
  let url = null
  url =router.resolve({
    path: '/assessTable',
    query: {
      id: item.id,
      isCheck:isCheck?isCheck:'',
    }
  })
  window.open(url.href)
}
//退回
const returnBth = (item: any) => {
  console.log(item)
  formReturn.value.id=item.id
  formReturn.value.reason = ""
  formReturn.value.shResult='2'
  dialogVisible5.value = true
}
//确认退回
const sureReturn = () => {
  statisticalcheck(formReturn.value).then((res: any) => {
    dialogVisible5.value = false
    if(res){
         ElMessage.success('已退回')
         getAssess()
    }  
  })
}
//通过
const  postPass=(item:any)=>{
  console.log(item)
  formReturn.value.id=item.checkInfoList[0].id
  formReturn.value.reason = ""
  formReturn.value.shResult='1'
  ElMessageBox.confirm(
    '确定通过?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      statisticalcheck(formReturn.value).then((res: any) => {
    if(res.code==200){
      ElMessage({
        type: 'success',
        message: '通过成功',
      })
    }
    getAssess()
  })
      
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消通过',
      })
    })
}
//上报
const toReport=(item:any)=>{
statisticalpublish(item.id).then((res) => {
  console.log(res)
    showSuccess.value = true
     getAssess()
    setTimeout(() => {
      showSuccess.value = false
    }, 1500);
  })
}
//补录
const showDig =async (item:any) => {
  //清除上一个上传的
  uploadFile.value=[]
  fileList.value=[]
  showDigs.value = item
  dialogVisible.value= true
  if(userRole=='3'){
  setFile.value = item.id
  }
  if(!item.files){
    filesName.value=[]
  }else{
    filesName.value=item.files.split(';')
  } 
}
// 获取文件名字和地址
const changeFile = (file: any) => {
  uploadFile.value.push(file.raw)
  console.log( uploadFile.value)
}
//删除文件
const beforeRemove = (file: any, uploadFiles: any) => {
  uploadFile.value.forEach((item: any, index: any) => {
    if (item.uid == file.raw.uid) uploadFile.value.splice(index, 1)
  })
}
//确定上传
const sureFile = async()=>{
if(uploadFile.value.length<=0) return
let formdata = new FormData() 
uploadFile.value.forEach((item: any) => formdata.append('files', item))
 let res:any = await wangeditorFile(formdata)
 console.log(res)
 if(res){
  if(showDigs.value.files==null){
    showDigs.value.files='';
    showDigs.value.files+=res
  }else{
    showDigs.value.files=showDigs.value.files+';'+res
  }
  let result:any = await upAssesFile(showDigs.value)
  dialogVisible.value= false
  getAssess()
  if(result.code=='200')return ElMessage.success('补录成功')
 }
 
}
//下载附件
const downFile= async (item:any)=>{
    let link = document.createElement('a')
    link.style.display = 'none';
    link.href = '/api/file/show/'+item;
    link.download = item;
    link.click()
    window.URL.revokeObjectURL(link.href)
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭弹窗?')
    .then(() => {
      dialogVisible.value= false
    })
    .catch(() => {
      // catch error
    })
}
//时间选择
const timeChoose = () => {
  console.log(value1.value)
  if (value1.value == null) {
    form.value.reportTimeStart = '';
    form.value.reportTimeEnd = '';
  } else {
    form.value.reportTimeStart = value1.value[0];
    form.value.reportTimeEnd = value1.value[1];
  }


}
onMounted(() => {
  getAssess().then(() => {
    getSelect()
  })
})

</script>